/**
 * @version 3.0.5
 * @Author lu-ch
 * @Email webwork.s@qq.com
 * 文档: https://www.quanzhan.co/luch-request/
 * github: https://github.com/lei-mu/luch-request
 * DCloud: http://ext.dcloud.net.cn/plugin?id=392
 * HBuilderX: beat-3.0.4 alpha-3.0.4
 */
import store from "../store/index";
import Request from "../utils/luch-request/luch-request/index";
import { showLoading, hideLoading } from "../utils/loading";
import { tip, linkTo } from "../utils/util";

const getStorage = (obj) => {
  let storage = "";
  try {
    storage = uni.getStorageSync(obj);
  } catch (e) {}
  return storage;
};

// 设置延迟毫秒显示LOADING
const delay = 300;

// 设置同时请求个数
let loadingCount = 0;

const http = new Request();
http.setConfig((config) => {
  config.baseURL = store.state.api;
  config.header = { "Content-Type": "application/json; charset=utf-8" };
  // 设置请求超时时间
  config.timeout = 10000;
  config.custom = {
    auth: true, // 是否传token
    loading: true, // 是否使用loading
  };

  return config;
});

let time = null;
let flag = false;

http.interceptors.request.use(
  (config) => {
    /* 请求之前拦截器。可以使用async await 做异步操作 */
    // console.log(store.state.userInfo.token, 'current token');
    config.header = {
      ...config.header,
    };

    // 设置请求开始时间
    config.metadata = {
      startTime: new Date(),
    };
    /**
     * custom {Object} - 自定义参数
     */
    if (config.custom.auth) {
      if (getStorage("personalInfo")) {
        config.header.Authorization = `bearer ${store.state.userInfo.token}`;
        config.header.platformid = `${store.state.userInfo.platform_id}`;
      }
    }

    // 累计请求个数
    loadingCount++;
    flag = true;
    time = setTimeout(() => {
      flag && showLoading("加载中");
    }, delay);

    return config;
  },
  (config) => {
    return Promise.reject(config);
  }
);

http.interceptors.response.use(
  async (response) => {
    // console.log('token', response.config.header.Authorization);
    // console.log('Authorization', response.header.Authorization || response.header.authorization);
    // 设置请求结束时间
    response.config.metadata.endTime = new Date();
    // 计算请求相应时间
    response.delay = response.config.metadata.endTime - response.config.metadata.startTime;
    // console.log(`本次请求响应时间为${response.delay}ms`);

    // 默认显示LOADING并且验证请求时间和请求个数
    // if (http.config.custom.loading && response.delay > delay && loadingCount > 0) {
    // showLoading('加载中');
    // }

    // 请求成功
    if (response.data.code == 200) {
      // 请求完成自减1
      loadingCount--;
      setTimeout(() => {
        hideLoading();
      }, 300);
    } else {
      hideLoading();
      tip({ title: response.data.message });
    }
    flag = false;
    clearTimeout(time);
    // TOKEN无痛刷新
    if (response.header.Authorization || response.header.authorization) {
      let user = uni.getStorageSync("personalInfo");
      user.token = response.header.Authorization ? response.header.Authorization.trim().split(" ")[1] : response.header.authorization.trim().split(" ")[1];
      store.state.userInfo.token = user.token;
      uni.setStorageSync("personalInfo", user);
    }

    return response;
  },
  (response) => {
    loadingCount = 0;
    hideLoading();

    if ([444, 450, 451].includes(response.data.code)) {
      tip({ title: response.data.message });
      return;
    }

    // 登陆信息过期
    if (response.data.code == 437 || response.data.code == 307 || response.data.code == 445) {
      tip({ title: "登录信息过期，请重新登录!" }, () => {
        setTimeout(() => {
          uni.removeStorageSync("personalInfo");
          linkTo("/pages/authentication/login", "noback");
        }, 1000);
      });
    }
    return Promise.reject(response);
  }
);

export { http };
